<template>
  <div class="schedule-task-manager">
    <el-tabs v-model="activeTab">
      <!-- 创建任务 -->
      <el-tab-pane label="创建任务" name="create">
        <TaskForm
            ref="createTaskFormRef"
            :form-data="taskForm"
            :is-editing="false"
            @submit="createTask"
            @cancel="$emit('close')"
            @reset="resetTaskForm" />
      </el-tab-pane>

      <!-- 任务列表 -->
      <el-tab-pane label="任务列表" name="list">
        <div class="task-list-header">
          <el-button @click="loadTasks" :icon="Refresh" size="small">刷新</el-button>
          <el-button @click="activeTab = 'create'" type="primary" :icon="Plus" size="small">新建任务</el-button>
        </div>

        <el-table :data="tasks" stripe style="width: 100%" v-loading="loadingTasks">
          <el-table-column prop="name" label="任务名称" width="180" show-overflow-tooltip></el-table-column>

          <el-table-column label="航线信息" width="180">
            <template #default="{ row }">
              <div class="route-info">
                <div class="route" v-if="row.departure && row.destination">
                  {{getCityName(row.departure)}} → {{getCityName(row.destination)}}
                </div>
                <div class="route" v-else>数据加载中...</div>
                <el-tag size="small" :type="row.tripType === 'oneway' ? 'info' : 'success'" v-if="row.tripType">
                  {{ row.tripType === 'oneway' ? '单程' : '往返' }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="动态配置" width="200">
            <template #default="{ row }">
              <div class="dynamic-config">
                <div class="config-item" v-if="row.crawlCycle">
                  <span class="label">周期:</span>
                  <span class="value">{{ row.crawlCycle }}天</span>
                </div>
                <div class="config-item" v-if="row.executionCount">
                  <span class="label">次数:</span>
                  <span class="value">{{ row.executionCount }}次</span>
                </div>
                <div class="config-item" v-if="row.baseDate">
                  <span class="label">基准:</span>
                  <span class="value">{{ row.baseDate }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="执行计划" width="160">
            <template #default="{ row }">
              <div class="cron-info" v-if="row.cronExpression">
                <div class="cron-text">{{ row.cronExpression }}</div>
                <div class="cron-desc">{{ getCronDescription(row.cronExpression) }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small" v-if="row.status">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="运行统计" width="220">
            <template #default="{ row }">
              <div class="run-stats">
                <div class="stat-item">
                  <span class="stat-label">总运行:</span>
                  <span class="stat-value">{{ row.totalRunCount || 0 }}次</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">成功:</span>
                  <span class="stat-value text-success">{{ row.successCount || 0 }}次</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">失败:</span>
                  <span class="stat-value text-danger">{{ row.failedCount || 0 }}次</span>
                </div>
                <div class="stat-item" v-if="row.lastRunAt">
                  <span class="stat-label">上次:</span>
                  <span class="stat-value">{{ formatRelativeTime(row.lastRunAt) }}</span>
                </div>
                <div class="stat-item" v-if="row.lastExecutionSummary">
                  <el-tooltip :content="row.lastExecutionSummary" placement="top">
                    <span class="summary-text">{{ row.lastExecutionSummary.substring(0, 20) }}...</span>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="240" fixed="right">
            <template #default="{ row }">
              <el-button-group>
                <el-tooltip content="编辑任务">
                  <el-button
                      size="small"
                      type="primary"
                      @click="editTask(row.id)"
                      :icon="Edit">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="暂停任务" v-if="row.status === 'ACTIVE'">
                  <el-button
                      size="small"
                      type="warning"
                      @click="toggleTask(row.id, 'pause')"
                      :icon="VideoPause">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="恢复任务" v-if="row.status === 'PAUSED'">
                  <el-button
                      size="small"
                      type="success"
                      @click="toggleTask(row.id, 'resume')"
                      :icon="VideoPlay">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="立即执行">
                  <el-button
                      size="small"
                      type="info"
                      @click="executeTask(row.id)"
                      :icon="CaretRight">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="查看日志">
                  <el-button
                      size="small"
                      @click="viewTaskLogs(row.id)"
                      :icon="Document">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除任务">
                  <el-button
                      size="small"
                      type="danger"
                      @click="deleteTask(row.id)"
                      :icon="Delete">
                  </el-button>
                </el-tooltip>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="tasks.length === 0 && !loadingTasks" class="empty-state">
          <el-empty description="还没有创建任务">
            <el-button type="primary" @click="activeTab = 'create'">创建第一个任务</el-button>
          </el-empty>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑任务对话框 -->
    <el-dialog
        v-model="showEditDialog"
        title="编辑定时任务"
        width="80%"
        top="5vh"
        :close-on-click-modal="false"
        :close-on-press-escape="false">
      <TaskForm
          ref="editTaskFormRef"
          v-if="showEditDialog"
          :form-data="editForm"
          :is-editing="true"
          @submit="updateTask"
          @cancel="cancelEdit" />
    </el-dialog>

    <!-- 任务日志对话框 -->
    <el-dialog v-model="showLogDialog" title="任务执行日志" width="80%" top="5vh">
      <div class="log-content">
        <el-table :data="taskLogs" stripe max-height="400">
          <el-table-column prop="executeTime" label="执行时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.executeTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="result" label="结果" width="100">
            <template #default="{ row }">
              <el-tag :type="row.result === 'SUCCESS' ? 'success' : 'danger'" size="small">
                {{ row.result === 'SUCCESS' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="耗时" width="100">
            <template #default="{ row }">
              {{ row.duration }}ms
            </template>
          </el-table-column>
          <el-table-column prop="message" label="消息" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Edit,
  VideoPause,
  VideoPlay,
  CaretRight,
  Document,
  Delete
} from '@element-plus/icons-vue'
import TaskForm from './TaskForm.vue'
import flightApi from '@/api/task'
import { formatRelativeTime, formatDate, getTaskStatusInfo, parseCronExpression } from '@/utils/helpers'
import cities from "@/utils/cityNames.js"
import cityNames from "@/utils/cityNames.js";

// Props & Emits
const emit = defineEmits(['task-created', 'close'])

// 响应式数据
const createTaskFormRef = ref()
const editTaskFormRef = ref()
const activeTab = ref('list')
const loadingTasks = ref(false)
const showEditDialog = ref(false)
const showLogDialog = ref(false)
const editingTaskId = ref('')

// 创建任务表单数据
const taskForm = reactive({
  name: '',
  departure: '',
  destination: '',
  tripType: 'roundtrip',
  roundTripDays: 7,
  adults: 1,
  children: 0,
  infants: 0,
  cabinClass: 'Y',
  baseDate: '',
  crawlCycle: 4,
  executionCount: 2,
  cronExpression: '0 0 8 * * ?',
  exportPath: './exports',
  exportLowestPriceOnly: false,
  emailNotification: false,
  emailRecipients: []
})

// 编辑任务表单数据
const editForm = reactive({
  name: '',
  departure: '',
  destination: '',
  tripType: '',
  roundTripDays: 7,
  adults: 1,
  children: 0,
  infants: 0,
  cabinClass: 'Y',
  baseDate: '',
  crawlCycle: 4,
  executionCount: 2,
  cronExpression: '',
  exportPath: '',
  exportLowestPriceOnly: false,
  emailNotification: false,
  emailRecipients: []
})

const tasks = ref([])
const taskLogs = ref([])

// 方法
const getCityName = (cityCode) => {
  if (!cityCode) return ''
  return cityNames[cityCode.toUpperCase()] || cityCode
}

async function createTask(formData) {
  try {
    const task = await flightApi.createScheduledTask(formData)
    ElMessage.success('任务创建成功')
    emit('task-created', task)
    resetTaskForm()
    await loadTasks()
    activeTab.value = 'list'
  } catch (error) {
    console.error('创建任务失败:', error)
    ElMessage.error('创建任务失败')
  }
}

async function editTask(taskId) {
  try {
    // 获取任务详情
    const response = await flightApi.getScheduledTask(taskId)

    let task = response.data
    // 填充编辑表单
    Object.assign(editForm, {
      name: task.name,
      departure: task.departure,
      destination: task.destination,
      tripType: task.tripType,
      roundTripDays: task.roundTripDays || 7,
      adults: task.adults,
      children: task.children,
      infants: task.infants,
      cabinClass: task.cabinClass,
      baseDate: task.baseDate,
      crawlCycle: task.crawlCycle,
      executionCount: task.executionCount,
      cronExpression: task.cronExpression,
      exportPath: task.exportPath,
      exportLowestPriceOnly: task.exportLowestPriceOnly,
      emailNotification: task.emailNotification,
      emailRecipients: task.emailRecipients || []
    })

    editingTaskId.value = taskId
    showEditDialog.value = true

  } catch (error) {
    console.error('获取任务详情失败:', error)
    ElMessage.error('获取任务详情失败')
  }
}

async function updateTask(formData) {
  try {
    await flightApi.updateScheduledTask(editingTaskId.value, formData);
    ElMessage.success('任务更新成功')
    showEditDialog.value = false
    await loadTasks()
  } catch (error) {
    console.error('更新任务失败:', error)
    ElMessage.error('更新任务失败')
  }
}

function cancelEdit() {
  showEditDialog.value = false
  editingTaskId.value = ''
}

async function loadTasks() {
  loadingTasks.value = true
  try {
    const response = await flightApi.getScheduledTasks()
    tasks.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error('加载任务列表失败')
    tasks.value = []
  } finally {
    loadingTasks.value = false
  }
}

async function deleteTask(taskId) {
  try {
    await ElMessageBox.confirm('确定要删除这个任务吗？删除后无法恢复。', '确认删除', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await flightApi.deleteScheduledTask(taskId)
    ElMessage.success('任务删除成功')
    await loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除任务失败:', error)
      ElMessage.error('删除任务失败')
    }
  }
}

async function toggleTask(taskId, action) {
  try {
    await flightApi.toggleScheduledTask(taskId, action)
    const actionText = action === 'pause' ? '暂停' : '恢复'
    ElMessage.success(`任务${actionText}成功`)
    await loadTasks()
  } catch (error) {
    console.error('切换任务状态失败:', error)
    ElMessage.error('操作失败')
  }
}

async function executeTask(taskId) {
  try {
    await ElMessageBox.confirm('确定要立即执行这个任务吗？', '确认执行', {
      confirmButtonText: '确定执行',
      cancelButtonText: '取消',
      type: 'info'
    })

    ElMessage.info('任务已开始执行，请稍候查看结果')
    await flightApi.executeScheduledTask(taskId)

    setTimeout(() => {
      loadTasks()
    }, 2000)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('执行任务失败:', error)
      ElMessage.error('执行任务失败')
    }
  }
}

async function viewTaskLogs(taskId) {
  try {
    const response = await flightApi.getTaskLogs(taskId)
    taskLogs.value = response.data
    showLogDialog.value = true
  } catch (error) {
    console.error('获取任务日志失败:', error)
    ElMessage.error('获取任务日志失败')
  }
}

function resetTaskForm() {
  Object.assign(taskForm, {
    name: '',
    departure: '',
    destination: '',
    tripType: 'roundtrip',
    roundTripDays: 7,
    adults: 1,
    children: 0,
    infants: 0,
    cabinClass: 'Y',
    baseDate: new Date().toISOString().split('T')[0],
    crawlCycle: 4,
    executionCount: 2,
    cronExpression: '0 0 8 * * ?',
    exportPath: './exports',
    exportLowestPriceOnly: false,
    emailNotification: false,
    emailRecipients: []
  })
}

function getStatusType(status) {
  return getTaskStatusInfo(status).type
}

function getStatusText(status) {
  return getTaskStatusInfo(status).label
}

function getCronDescription(cron) {
  return parseCronExpression(cron)
}

function formatDateTime(time) {
  return formatDate(new Date(time), 'YYYY-MM-DD HH:mm:ss')
}

// 生命周期
onMounted(() => {
  loadTasks()
  resetTaskForm()
})
</script>

<style scoped>
/* 原有样式保持不变 */
.config-section {
  margin-bottom: 20px;
  background: #fafafa;
}

.task-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.route-info {
  font-size: 12px;
}

.route {
  font-weight: bold;
  margin-bottom: 4px;
  color: #0969da;
}

.dynamic-config {
  font-size: 12px;
}

.config-item {
  display: flex;
  margin-bottom: 4px;
}

.config-item:last-child {
  margin-bottom: 0;
}

.label {
  width: 40px;
  color: #656d76;
}

.value {
  color: #24292f;
  font-weight: 500;
}

.cron-info {
  font-size: 12px;
}

.cron-text {
  font-family: monospace;
  color: #0969da;
  margin-bottom: 4px;
}

.cron-desc {
  color: #656d76;
}

.run-stats {
  font-size: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.stat-item:last-child {
  margin-bottom: 0;
}

.stat-label {
  width: 50px;
  color: #656d76;
}

.stat-value {
  color: #24292f;
  flex: 1;
}

.text-success {
  color: #1a7f37;
}

.text-danger {
  color: #cf222e;
}

.summary-text {
  font-size: 11px;
  color: #656d76;
  cursor: pointer;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.log-content {
  max-height: 500px;
  overflow-y: auto;
}
</style>